const app = getApp();
const regeneratorRuntime = global.regeneratorRuntime = require("../libs/regenerator");
const co = require('../libs/co');

Page({
  data:{
    hidden:false,
    address:{},
    hasAddress: false,
    total:0,
    products:[],
    payTypes: ["在线支付", "货到付款"],
    payIndex: 0,
    shipTypes: [{"id":1,"name":"普通快递","amount":0},{"id":2,"name":"顺丰","amount":0},{"id":3,"name":"EMS","amount":0}],
    shipIndex: 0,
    selectShipId: 1,
    selectShipName: "普通快递",
    selectShipAmount: 0,
  },

  onReady() {

  },
  onLoad: function(options) {
      app.launchOptions = options;
      /* !Do not Remove the follow line, used for build tool.*/
      let skuIds = options.skuId;
      this.loadProduct(skuIds);
  },
  loadProduct: function (skuIds) {
    const self = this;
    co(function *() {
        let cartService = require("../services/mall/cartService");
        let products = yield cartService.getSelectCart(skuIds);
        self.setData({
            hidden:true,
            products: products
        });
        self.getTotalPrice();
    });
  },

  onShow:function(){
    const self = this;
    wx.getStorage({
      key:'address',
      success(res) {
        self.setData({
          address: res.data,
          hasAddress: true
        })
      }
    })
  },

  /**
   * 计算总价
   */
  getTotalPrice() {
    let products = this.data.products;
    let total = 0;
    for(let i = 0; i < products.length; i++) {
      total += products[i].selectedNumber * products[i].selectedAmount;
    }
    console.log(total);
    this.setData({
      total: total
    })
  },
  toAddress:function() {
    const self = this;
    wx.chooseAddress({
      success: function (res) {
        let address = self.data.address;
        address.name = res.userName;
        address.phone = res.telNumber;
        address.code = res.postalCode;
        address.provinceName = res.provinceName;
        address.cityName = res.cityName;
        address.countyName = res.countyName;
        address.detail = res.detailInfo;
        self.setData({
          address: address,
          hasAddress: true
        })
      }
    });
  },
  toPay:function() {
    let info = {};
    if (this.data.address.name == undefined) {
      wx.showModal({
        title: '提示',
        content: '请选择收货地址',
        text:'center',
        showCancel: false
      });
      return;
    }
    info.shipType = this.data.selectShipId;
    info.shipAmount = this.data.selectShipAmount;
    info.paymentType = this.data.payIndex + 1;
    info.consignee = this.data.address.name;
    info.mobile = this.data.address.phone;
    info.province = this.data.address.provinceName;
    info.city = this.data.address.cityName;
    info.district = this.data.address.countyName;
    info.address = this.data.address.detail;
    info.products = this.data.products;
    info.productAmount = this.data.total;
    info.orderAmount = this.data.total + this.data.selectShipAmount;
    info.payAmount = this.data.total + this.data.selectShipAmount;

    var that = this;
    co(function *() {
        let body = that.data.products[0].productName;
        let orderService = require("../services/mall/orderService");
        let ret = yield orderService.addOrder(info);
        if (ret.orderNum != null) {
          that.prePay(ret.orderNum,body,info.payAmount);
        }
        console.log(ret);
    });

    /*wx.showModal({
      title: '提示',
      content: '本系统只做演示，支付系统已屏蔽',
      text:'center',
      complete() {
        wx.switchTab({
          url: '/page/component/user/user'
        })
      }
    })*/
  },
  prePay: function (orderNum,body,price) {
    var that = this;
    co(function *() {
        let orderService = require("../services/mall/orderService");
        let ret = yield orderService.prePay(orderNum,body,price);
        if (ret.apiStatus.statusCode == 0) {
          //that.prePay(ret.result.orderNum);
          let json = ret.result;
          wx.requestPayment(
              {
              'timeStamp': json.timestamp,
              'nonceStr': json.nonceStr,
              'package': json.pck,
              'signType': 'MD5',
              'paySign': json.sign,
              'success':function(res){
                 console.log("success");
              },
              'fail':function(res){

              },
              'complete':function(res){

              }
            });
        }
        console.log(ret);
    });
  },
  bindPayTypeChange: function(e) {
        this.setData({
            payIndex: parseInt(e.detail.value)
        });
  },
  bindShipTypeChange: function(e) {
        let ship = this.data.shipTypes[e.detail.value];
        console.log(ship);
        this.setData({
            shipIndex: e.detail.value,
            selectShipId: ship.id,
            selectShipName: ship.name,
            selectShipAmount: ship.amount
        });
  }
})
